package com.ftp.util;

import com.ftp.config.FtpConfig;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.StringTokenizer;

/**
 * Created by kedaom on 2018/10/25.
 */
public class FtpUtil {

    private  static FTPClient ftpClient = new FTPClient();

    static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

  /*  static {
        try {
            ftpClient.connect("192.168.137.1",21);
            ftpClient.login("kedaom", "xyz"); //登录ftp服务器
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/

    public static void init(FtpConfig ftpConfig){
        try {
            ftpClient.connect(ftpConfig.getIp(),ftpConfig.getPort());
            ftpClient.login(ftpConfig.getUser(), ftpConfig.getPass()); //登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
            if(!FTPReply.isPositiveCompletion(replyCode)){
                logger.error("connect failed...ftp服务器:"+ftpConfig.getIp()+":"+ftpConfig.getPort());
            }
            logger.info("connect successfu...ftp服务器:"+ftpConfig.getIp()+":"+ftpConfig.getPort());

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void ftpUpload(File file,String basePath) {
        try {
            createDirectory(basePath);
            ftpClient.setBufferSize(1024);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(getBytes(file));
            String FTPFileName = new String(file.getName().getBytes(),"iso-8859-1");
            ftpClient.storeFile(FTPFileName,inputStream);
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param basePath
     * @return
     */
    public static synchronized boolean createDirectory(String basePath) {
        try {
            ftpClient.changeWorkingDirectory(File.separator+"SXYQ"+File.separator);
            StringTokenizer s = new StringTokenizer(basePath, File.separator);
            while (s.hasMoreElements()){
                String path = new String(((String) s.nextElement()).getBytes(),"iso-8859-1");
                boolean isBase =  ftpClient.changeWorkingDirectory(path);
                if (!isBase){
                    isBase = ftpClient.makeDirectory(path);
                    if (!isBase){
                        logger.error("创建目录{}失败",path);
                        return false;
                    }
                    ftpClient.changeWorkingDirectory(path);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }
    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(File file){
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    /*public static void main(String[] args) throws  Exception{
        File file = new File("F:\\temp\\0.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1000];
        int n;
        while ((n = fileInputStream.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        byte[] buffer = bos.toByteArray();
        ftpUpload(buffer,"001"+File.separator+"01"+File.separator,"1.png");
        ftpUpload(buffer,"001"+File.separator+"02"+File.separator,"1.png");
        ftpUpload(buffer,"002"+File.separator+"01"+File.separator,"1.png");
    }*/
}
